package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Title: TCPclient
 * @Author 郑雨杭
 * @Package TCP
 * @Date 2024/7/11 21:15
 * @description: TCP客户端
 */
public class TCPclient {
    //创建socket对象
    private Socket socket = null;
    //初始化socket对象，绑定服务器的ip和端口
    public TCPclient(String ip, int port) throws IOException {
        socket = new Socket(ip,port);
    }
    private void stact(){
        //打印提示信息
        System.out.println("客户端启动");
        //标准输入流，用于接收用户请求
        Scanner scanner = new Scanner(System.in);
        //获取输入输出流并且封装成Scanner和PrintWriter，放在try里避免资源泄露
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();
             PrintWriter writer = new PrintWriter(outputStream);
             Scanner input = new Scanner(inputStream)) {
            //循环发送请求
            while (true) {
                //提示输入请求
                System.out.print("请输入：");
                //用户输入请求
                String req = scanner.next();
                //将请求发送给服务器
                writer.println(req);
                //刷新缓冲区
                writer.flush();
                //得到服务器的响应
                String resp = input.next();
                //将响应输出到控制台
                System.out.println(resp);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭连接，避免资源泄露
            scanner.close();
        }
    }

    //绑定服务器IP和端口，并且启动客户端
    public static void main(String[] args) throws IOException {
        new TCPclient("127.0.0.1",9090).stact();
    }
}
